//
//  ConfigViewController.m
//  telefonista
//
//  Created by Vinícius Daly Felizardo on 22/10/13.
//  Copyright (c) 2013 Vinícius Daly Felizardo. All rights reserved.
//

#import "ConfigViewController.h"

#import "AppDelegate.h"
#import "TelNumber+Create.h"
#import "Region+Create.h"
#import "ChooseObjectDBViewController.h"
#import "LongDistanceOperator+Create.h"
#import "Country+Create.h"
#import <UIKit/UIKit.h>

@interface ConfigViewController ()

@end

@implementation ConfigViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
//
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)viewDidAppear:(BOOL)animated
{
    [self.tableView reloadData];
}

#define NUMBER_OF_ROWS 4
#define ROW_CHOOSE_CURRENT_LOCATION 0
#define ROW_EDIT_NUMBER 1
#define ROW_CHOOSE_CARRIER 2
#define ROW_PREFERRED_LDO 3


- (void)chooseObjectDBVC:(ChooseObjectDBViewController *)controller configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
    if ([controller.fetchRequest.entityName isEqualToString:@"Region"]) {
        Region * region =  [controller.fetchedResultsController objectAtIndexPath:indexPath];
        cell.detailTextLabel.text = region.code.stringValue;
        cell.textLabel.text = region.name;
    }
    if ([controller.fetchRequest.entityName isEqualToString:@"LongDistanceOperator"]) {
        LongDistanceOperator * ldo =  [controller.fetchedResultsController objectAtIndexPath:indexPath];
        cell.detailTextLabel.text = ldo.code.stringValue;
        cell.textLabel.text = ldo.name;
    }
}

- (void)chooseObjectDBVC:(ChooseObjectDBViewController *)controller tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([controller.fetchRequest.entityName isEqualToString:@"Region"]) {
        Region * region =  [controller.fetchedResultsController objectAtIndexPath:indexPath];
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        
        NSURL *moIDURL = [[region objectID] URIRepresentation];
        
        NSString *moIDURLString = [moIDURL absoluteString];
        
        [userDefaults setObject:moIDURLString forKey:PREF_REGION];
        
        [userDefaults synchronize];
    }
    if ([controller.fetchRequest.entityName isEqualToString:@"LongDistanceOperator"]) {
        LongDistanceOperator * ldo =  [controller.fetchedResultsController objectAtIndexPath:indexPath];
        
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        
        NSURL *moIDURL = [[ldo objectID] URIRepresentation];
        
        NSString *moIDURLString = [moIDURL absoluteString];
        
        [userDefaults setObject:moIDURLString forKey:PREF_LDO];
        
        [userDefaults synchronize];

    }
    
}

- (NSIndexPath *)defaultRowForChooseObjectDBVC:(ChooseObjectDBViewController *)controller
{
    if ([controller.fetchRequest.entityName isEqualToString:@"Region"]) {
        Region* userRegion = [Region userRegionWithContext:[ self managedObjectContext ]];
        return [controller.fetchedResultsController indexPathForObject:userRegion];
    }
    
    if ([controller.fetchRequest.entityName isEqualToString:@"LongDistanceOperator"]) {
        LongDistanceOperator* userLDO = [LongDistanceOperator userDefaultLongDistanceOperatorWithContext:[ self managedObjectContext ]];
        return [controller.fetchedResultsController indexPathForObject:userLDO];
        
    }
    return nil;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return NUMBER_OF_ROWS;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    switch (indexPath.row) {
        case ROW_CHOOSE_CURRENT_LOCATION:
        {
            
            UINavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"ChooseObjectDBViewController"];
            ChooseObjectDBViewController *dbViewController = (ChooseObjectDBViewController *)[[navigationController viewControllers] objectAtIndex:0];
            dbViewController.delegate = self;
            
            
            
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
            NSEntityDescription *entity = [NSEntityDescription
                                           entityForName:@"Region" inManagedObjectContext:[self managedObjectContext]];
            [fetchRequest setEntity:entity];
            
            
            Country* brazil = [Country countryWithCode:55 withContext:[ self managedObjectContext]];
            
            [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"country = %@", brazil]];
            
            NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                                      initWithKey:@"code" ascending:YES];
            [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
            
            dbViewController.fetchRequest = fetchRequest;
            
            dbViewController.title = @"Onde estou";
            
            
            [self presentViewController:navigationController animated:YES completion:nil];
            
            break;
        }
        case ROW_EDIT_NUMBER:
        {
            [self performSegueWithIdentifier:@"editMyNumber" sender:self];
            
            break;
        }
        case ROW_CHOOSE_CARRIER:
        {
            [self performSegueWithIdentifier:@"chooseCarrier" sender:self];
            
            break;
        }
        case ROW_PREFERRED_LDO:
        {
            
            UINavigationController *navigationController = [self.storyboard instantiateViewControllerWithIdentifier:@"ChooseObjectDBViewController"];
            ChooseObjectDBViewController *dbViewController = (ChooseObjectDBViewController *)[[navigationController viewControllers] objectAtIndex:0];
            dbViewController.delegate = self;
            
            
            
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
            NSEntityDescription *entity = [NSEntityDescription
                                           entityForName:@"LongDistanceOperator" inManagedObjectContext:[self managedObjectContext]];
            [fetchRequest setEntity:entity];
            
            
            Country* brazil = [Country countryWithCode:55 withContext:[ self managedObjectContext]];
            
            [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"country = %@", brazil]];
            
            NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                                      initWithKey:@"code" ascending:YES];
            [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
            
            dbViewController.fetchRequest = fetchRequest;
            
            dbViewController.title = @"Operadora DDD padrão";
            
            [self presentViewController:navigationController animated:YES completion:nil];
            
            break;
        }
    }
}

- (UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *advancedId = @"Advanced";
    
    UITableViewCell *cell;
    switch (indexPath.row)
    {
        case ROW_CHOOSE_CURRENT_LOCATION:
        {
            Region* region = [Region userRegionWithContext:[self managedObjectContext]];
            
            cell = [tableView dequeueReusableCellWithIdentifier:advancedId];
            if (cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:advancedId];
            }
            ((AdvancedSettingCell*)cell).title.text = @"Onde Estou";
            
            if (region) {
                ((AdvancedSettingCell*)cell).currentState.text = [NSString stringWithFormat:@"%@ (%d)", region.name, [region.code intValue]];
            }
            break;
        }
        case ROW_EDIT_NUMBER:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:advancedId];
            if (cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:advancedId];
            }
            
            TelNumber* telNumber = [TelNumber
                                    userTelNumberWithContext:[self managedObjectContext]];
            
            ((AdvancedSettingCell*)cell).title.text = @"Meu Número";
            if (telNumber) {
            ((AdvancedSettingCell*)cell).currentState.text = [NSString stringWithFormat:@"(%d) %@", [telNumber.regionFrom.code intValue],
                                                             telNumber.number];
            }
            break;
        }
        case ROW_CHOOSE_CARRIER:
        {
            cell = [tableView dequeueReusableCellWithIdentifier:advancedId];
            if (cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:advancedId];
            }
            ((AdvancedSettingCell*)cell).title.text = @"Minha Operadora";
            break;
        }
        case ROW_PREFERRED_LDO:
        {
            LongDistanceOperator* ldo = [LongDistanceOperator userDefaultLongDistanceOperatorWithContext:[self managedObjectContext]];
            
            cell = [tableView dequeueReusableCellWithIdentifier:advancedId];
            if (cell == nil)
            {
                cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:advancedId];
            }
            ((AdvancedSettingCell*)cell).title.text = @"Operadora DDD padrão";
            
            if (ldo) {
                ((AdvancedSettingCell*)cell).currentState.text = [NSString stringWithFormat:@"%@ (%d)", ldo.name, [ldo.code intValue]];
            }
            break;
            
        }
    }
    
    return cell;
}


- (NSManagedObjectContext*) managedObjectContext
{
    return [(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
